package com.example.android_web_4;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.entity.TbClass;
import com.example.utils.BitMapUtils;
import com.example.utils.CallBack;
import com.example.utils.FileUtils;
import com.example.utils.HttpUtils;
import com.example.utils.UploadUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.w3c.dom.Text;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddStuActivity extends Activity {

    private EditText sname,sage,sintime;
    private CheckBox cb1,cb2,cb3;
    private Spinner spinner;
    private ImageView simage;
    private RadioGroup rgsex;
    private String ssex="男";
    private String imagePath;
    private String cid;
    String basePath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_stu);
        basePath="http://"+getResources().getString(R.string.ipaddress)+":"+getResources().getString(R.string.serverport)+"/" +
                getResources().getString(R.string.project);
        sname=(EditText)findViewById(R.id.sname);
        sage=(EditText)findViewById(R.id.sage);
        sintime=(EditText)findViewById(R.id.sintime);
        cb1=(CheckBox)findViewById(R.id.shobby_1);
        cb2=(CheckBox)findViewById(R.id.shobby_2);
        cb3=(CheckBox)findViewById(R.id.shobby_3);
        spinner=(Spinner)findViewById(R.id.cid);
        simage=(ImageView)findViewById(R.id.userImage);
        rgsex=(RadioGroup)findViewById(R.id.rgsex);
        rgsex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton rb=(RadioButton)findViewById(i);
                ssex=rb.getText().toString();
            }
        });

        //调用Web方法查询所有班级
        String url=basePath+"/TbClassServlet?method=classList";
        HttpUtils.doGet(url, new CallBack() {
            @Override
            public void success(final String str) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List<TbClass> clslist=new Gson().fromJson(str,new TypeToken<List<TbClass>>(){}.getType());
                        List<Map<String,Object>> list=new ArrayList<Map<String, Object>>();
                        for (int i=0;i< clslist.size();i++){
                            TbClass cls=clslist.get(i);
                            Map<String,Object> map=new HashMap<String, Object>();
                            map.put("_id",cls.get_id());
                            map.put("cname",cls.getCname());
                            list.add(map);
                        }
                        String[] from={"_id","cname"};
                        int[] to={R.id.cid,R.id.cname};
                        SimpleAdapter adapter=new SimpleAdapter(AddStuActivity.this,list,R.layout.layout_spinner_class,from,to);
                        spinner.setAdapter(adapter);
                    }
                });
            }
            @Override
            public void failed(String str) {
            }
        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                LinearLayout linear=(LinearLayout)view;
                TextView id=(TextView)linear.findViewById(R.id.cid);
                cid=id.getText().toString();
                Toast.makeText(AddStuActivity.this, "cid="+cid, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //选择图像
    public void selectImage(View view){
        Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){
            if(data!=null) {
                Uri uri = data.getData();//获取选择的图片Uri
                imagePath = FileUtils.getPath(this, uri);//获取图片真实保存位置
                simage.setImageBitmap(BitMapUtils.getSmallBitmap(imagePath));
            }
        }
    }

    public void doAddStu(View view) throws UnsupportedEncodingException {
        String name=sname.getText().toString();
        int age=Integer.parseInt(sage.getText().toString());
        String intime=sintime.getText().toString();
        String hobby="";
        if(cb1.isChecked())
            hobby=cb1.getText().toString()+",";
        if(cb2.isChecked())
            hobby=hobby+cb2.getText().toString()+",";
        if(cb3.isChecked())
            hobby=hobby+cb3.getText().toString()+",";
        if(hobby.length()>0)
            hobby=hobby.substring(0,hobby.length()-1);

        //执行添加学生并上传文件
        String data="uname="+ URLEncoder.encode(name,"UTF-8")+"&uage="+age+"&usex="+URLEncoder.encode(ssex,"UTF-8")+"" +
                "&uhobby="+URLEncoder.encode(hobby,"UTF-8")+"&uintime="+intime+"&cid="+cid;
        Log.i("add data",data);
        final String url=basePath+"/TbStuServlet?method=addStu&"+data;
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String str=UploadUtils.uploadFile(new File(imagePath),url);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AddStuActivity.this, "str="+str, Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }).start();
    }
}
